package com.qh.resourcehub.utils;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

public class CasXmlUtil {

    public static String extractUsername(String xml) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

        NodeList success = doc.getElementsByTagName("cas:authenticationSuccess");
        if (success.getLength() > 0) {
            NodeList userList = doc.getElementsByTagName("cas:user");
            if (userList.getLength() > 0) {
                return userList.item(0).getTextContent();
            }
        }
        return null;
    }
}
